/*
* Copyright 2010 ANDAGO INGENIERIA S.L.
*
* Licensed under the EUPL, Version 1.1 only (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/

package com.andago.alohaui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import com.andago.utils.NomenclatureIEEE;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.andago.bean.Measurement;
import com.andago.contentProviders.Measurements;
import com.andago.contentProviders.Measurements.MeasurementsData;
import com.andago.services.GoogleHealthService;
import com.andago.services.VitalSignsWS;

public class MeasuresActivity extends Activity implements OnClickListener {


	ProgressDialog progress_dialog = null;
	AlertDialog alert_dialog = null;
	boolean enviar = false;
	boolean google;
	boolean andago;
	boolean both;
	String userAndago;
	String userGoogle;
	String passGoogle;	
	ArrayList<Measurement> measurementsList;
	public static HashMap<String, Measurement>  measurementsHashMap;
	
	ArrayList<String> items;
	
	String measurement_name;
	ArrayList<String> values;
	ArrayList<Integer> attributes;
	ArrayList<Integer> units;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.measures);

		System.out.println("onCreate MeasuresActivity ");

		/* adding button */

		Button button = (Button) findViewById(R.id.sendButton);
		button.setOnClickListener(this);

	    
	    
	    String measurement="";    	
    	Bundle extras  = getIntent().getExtras();
 
    	
    	values = extras.getStringArrayList(getString(R.string.measurement_bundle));
    	units = extras.getIntegerArrayList(getString(R.string.unit_bundle));  
    	attributes = extras.getIntegerArrayList(getString(R.string.attribute_bundle));
    	String selection = extras.getString(getString(R.string.selection_bundle));
    	
    	
    	for (int j=0; j<attributes.size(); j++){
    		System.out.println("attribute "+ j +" = " + attributes.get(j));	
    	}
    	
    	for (int z=0; z<values.size(); z++){
    		System.out.println("values "+ z +" = " + values.get(z));
    	}
    	
    	for (int k=0; k<units.size(); k++){
    		System.out.println("units "+ k +" = " + units.get(k));
    	}
    	
    	
    	System.out.println("measurementArray Size "+ values.size());
    	
		if (values.size() >0){
			

			Iterator<String> i = values.iterator();
			Iterator<Integer> iUnits = units.iterator();
			Iterator<Integer> iAttributes = attributes.iterator();			
			items = new ArrayList<String>();


		
			while (i.hasNext()&&iUnits.hasNext()&&iAttributes.hasNext()){
				

				measurement = (String) i.next();

				
				
				
				String unit = NomenclatureIEEE.calculateUnit(iUnits.next());
				String attribute = NomenclatureIEEE.calculateAttribute(iAttributes.next());
				measurementsHashMap = new HashMap<String, Measurement>();
				Date now=new Date(System.currentTimeMillis());
	    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.S");
				Measurement m = new Measurement (attribute, measurement, unit, sdf.format(now));
				measurementsHashMap.put(attribute,m);	
				
				items.add(attribute + ": " + measurement + " " + unit);
				
				System.out.println("measurementArray "+ measurement);
				
				if (selection.equals(getString(R.string.measures_selection))){
					
					TextView text = new TextView(this);
					text.setTextSize(25);
					text.setTextColor(Color.WHITE);
					text.setGravity(Gravity.CENTER_VERTICAL);
					text.setText(attribute + ": " + measurement + " " + unit);
				

					LinearLayout myLayaout = (LinearLayout) findViewById(R.id.layaout_text);

					myLayaout.addView(text);
				}

			}

				
			if (selection.equals(getString(R.string.devices_selection))){
				
				ListView lv = (ListView) findViewById(R.id.list_measures);
				lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice, items));
				lv.setTextFilterEnabled(true); 
				lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
				lv.setItemChecked(0, true);
				lv.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						// TODO Auto-generated method stub
						 System.out.println("onItemClick "+ position + " "+ items.get(position) + " " +items.get(position).split(":", 2)[0]);
						 Measurement m= measurementsHashMap.get(items.get(position) + " " +items.get(position).split(":", 2)[0]);	
						 
						 
						
					}
					
				});	
				
			

			} 
			
		}
			 
	}       

		


	

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		/* Options dialog */

		AlertDialog.Builder builderDialog = new AlertDialog.Builder(
				MeasuresActivity.this);
		builderDialog.setMessage(
				getString(R.string.data_stored))
				.setCancelable(false).setPositiveButton(getString(R.string.yes_button),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								MeasuresActivity.this.enviar = true;
								dialog.cancel();
								showOptions();
							}

						}).setNegativeButton(getString(R.string.no_button),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								measurementsList.clear();
								dialog.cancel();
								showOptions();
							}
						});


		measurementsList = checkLocalDataAll();

		if (!(measurementsList.isEmpty())) {			
	 
			alert_dialog = builderDialog.create();
			alert_dialog.show();
			
		} else
			showOptions();

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		stopService(new Intent(getString(R.string.droidEvent)));
		super.onDestroy();
	}

	private void showOptions() {

		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());
		userAndago = settings.getString("ausername", "");
		userGoogle = settings.getString("gusername", "");
		passGoogle = settings.getString("gpassword", "");

		CharSequence[] items = null;

		if ((userAndago != "") && ((userGoogle != "") && (passGoogle != ""))) {
			CharSequence[] i = { "Andago Health Service",
					"Google Health Service" };
			items = i;
		} else if ((userAndago == "")
				&& ((userGoogle != "") && (passGoogle != ""))) {
			CharSequence[] i = { "Google Health Service" };
			google = true;
			items = i;
		} else if ((userAndago != "")
				&& ((userGoogle == "") || (passGoogle == ""))) {
			CharSequence[] i = { "Andago Health Service" };
			andago = true;
			items = i;
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setTitle(getString(R.string.title_services));

		builder.setItems(items, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int item) {
		
				if (both) {
					if (item == 0) {
						dialog.cancel();
						sendAndago();
					} else if (item == 1) {
						dialog.cancel();
						sendGoogle();
					}
				} else {
					if (google){
						dialog.cancel();
						sendGoogle();
					}else if (andago){
						dialog.cancel();
						sendAndago();
					}
				}

			}
		});

		// builder.show();
		System.out.println("*********************Services: " + items.length);
		if (items.length == 1)
			both = false;
		else if (items.length == 2)
			both = true;

		AlertDialog alert = builder.create();
		alert.show();

	}

	private void sendAndago() {
		

		progress_dialog = ProgressDialog.show(MeasuresActivity.this,
				"Sending...", "sending..", true, false);
		Measurement me = null;

		try {
			VitalSignsWS ws = new VitalSignsWS(userAndago);
			if (enviar) {
				for (int i = 0; i < measurementsList.size(); i++) {
					me = new Measurement(measurementsList.get(i).getVariable(),
							measurementsList.get(i).getValue(),
							measurementsList.get(i).getUnit(), measurementsList
									.get(i).getDate());
					boolean variableAccepted = ws
							.checkVariable(me.getVariable());
					if (variableAccepted) {
						ws.sendVitalSigns(me);
						deleteMeasure(me);
					} else
						Toast
								.makeText(
										getApplicationContext(),
										getString(R.string.error_var)
												+ " "+me.getVariable(),
										Toast.LENGTH_SHORT).show();

				}
			}

			for (int i = 0; i < values.size(); i++) {

				Date now = new Date(System.currentTimeMillis());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.S");
				String unit = NomenclatureIEEE.calculateUnit(units.get(i));
				String att = NomenclatureIEEE.calculateAttribute(attributes.get(i));
				boolean variableAccepted = ws.checkVariable(att);
				System.out.println(sdf.format(now));
				if (variableAccepted) {
					me = new Measurement(att, values.get(i), unit, sdf.format(now));
					ws.sendVitalSigns(me);
				} else
					Toast.makeText(getApplicationContext(),
							getString(R.string.error_var) + " "+att,Toast.LENGTH_LONG).show();
			}
			progress_dialog.dismiss();
			Intent intent = new Intent();
			intent.setClassName("com.andago.alohaui",
					"com.andago.alohaui.AlohaMainUI");
			startActivity(intent);
			this.finish();
		} catch (Exception e) {
			/**************** Error con el servicio de Andago, se guarda en local ****************************/
			progress_dialog.dismiss();
			storeLocally(me);
		}

	}


	private void sendGoogle() {

		progress_dialog = ProgressDialog.show(MeasuresActivity.this,
				"Sending...", "sending..", true, false);
		Measurement me = null;
		
		try {
			if (enviar)
				deleteRecords();

			for (int i = 0; i < values.size(); i++) {

				Date now = new Date(System.currentTimeMillis());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.S");
				String unit = NomenclatureIEEE.calculateUnit(units.get(i));
				String att = NomenclatureIEEE.calculateAttribute(attributes.get(i));
				me = new Measurement(att, values.get(i), unit, sdf.format(now));
				measurementsList.add(me);
			}

			GoogleHealthService servGoogle = new GoogleHealthService();
			int codeLogin = servGoogle.loginService(userGoogle, passGoogle);

			if (codeLogin == 200) {
				int codeSend = servGoogle.sendMeasurements(measurementsList);
				if (codeSend != 201) {

					/**************** Error al enviar, se guarda en local ****************************/
					progress_dialog.dismiss();
					storeLocally(me);
				} else {
					progress_dialog.dismiss();
					Intent intent = new Intent();
					intent.setClassName("com.andago.alohaui",
							"com.andago.alohaui.AlohaMainUI");
					startActivity(intent);
					this.finish();
				}
			} else {

				/**************** Error al loguearse, se guarda en local ****************************/
				progress_dialog.dismiss();
				storeLocally(me);
			}

		} catch (Exception e) {

			/**************** Error con el servicio de Google, se guarda en local ****************************/
			progress_dialog.dismiss();
			storeLocally(me);
		}

	}

	private void storeLocally(final Measurement m) {
		AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
		localBuilder.setMessage(R.string.local_DB).setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						insertIntoDB(m);
						dialog.cancel();

						Intent intent = new Intent();
						intent.setClassName("com.andago.alohaui","com.andago.alohaui.AlohaMainUI");
						startActivity(intent);
						MeasuresActivity.this.finish();
					}
				});

		AlertDialog alert = localBuilder.create();
		alert.show();

	}


	/******************************************************** MÉTODOS BASE DE DATOS ***********************************************************************/

	/**
	 * Método que guarda en la BD la medida realizada
	 * 
	 * @param m Medida
	 */

	private void insertIntoDB(Measurement m) {

		ContentValues values = new ContentValues();

		values.put(Measurements.MeasurementsData.VAR_NAME, m.getVariable());
		values.put(Measurements.MeasurementsData.VALUE, m.getValue());
		values.put(Measurements.MeasurementsData.UNIT, m.getUnit());
		values.put(Measurements.MeasurementsData.TEST_DATE, m.getDate());

		Uri mURI = getContentResolver().insert(MeasurementsData.CONTENT_URI,
				values);
		if (mURI == null) {
			Log.e("BD", "Failed to insert a new test result into "
					+ getIntent().getDataString());
			finish();
			return;
		}

	}



	/**
	 * Método que comprueba si hay datos sin enviar para todas las variables
	 * 
	 * @return Lista de Mediciones sin enviar
	 */

	private ArrayList<Measurement> checkLocalDataAll() {

		ArrayList<Measurement> localMeasurements = new ArrayList<Measurement>();
		Cursor cur = getContentResolver().query(MeasurementsData.CONTENT_URI,
				null, null, null, MeasurementsData.TEST_DATE + " ASC");
		if (cur.moveToFirst()) {
			do {
				Measurement m = new Measurement(
						cur.getString(cur.getColumnIndex(MeasurementsData.VAR_NAME)),
						cur.getString(cur.getColumnIndex(MeasurementsData.VALUE)),
						cur.getString(cur.getColumnIndex(MeasurementsData.UNIT)),
						cur.getString(cur.getColumnIndex(MeasurementsData.TEST_DATE)));

				localMeasurements.add(m);
			} while (cur.moveToNext());

		}

		return localMeasurements;
	}

	

	/**
	 * Método que borra los datos que había sin enviar, una vez enviados
	 */

	private void deleteRecords() {
		getContentResolver().delete(MeasurementsData.CONTENT_URI, null, null);
	}

	/**
	 * Método que borra una medida, una vez enviada
	 * 
	 * @param m Medida
	 */
	private void deleteMeasure(Measurement m) {

		String id = "";
		String[] projection = new String[] { MeasurementsData._ID };
		String where = MeasurementsData.VAR_NAME + " = ? AND "
				+ MeasurementsData.VALUE + " = ? AND "
				+ MeasurementsData.TEST_DATE + " = ?";
		String[] args = new String[] { m.getVariable(), m.getValue(),
				m.getDate() };
		Cursor cur = getContentResolver().query(MeasurementsData.CONTENT_URI,
				projection, where, args, MeasurementsData.TEST_DATE + " ASC");
		if (cur.moveToFirst()) {
			do {
				id = cur.getString(cur.getColumnIndex(MeasurementsData._ID));
			} while (cur.moveToNext());
		}

		Uri myMeasure = Uri.withAppendedPath(MeasurementsData.CONTENT_URI, id);
		getContentResolver().delete(myMeasure, null, null);
	}

}
